package com.xiong.wuliao.homefragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.xiong.wuliao.R;
import com.xiong.wuliao.SpecialActivity;
import com.xiong.wuliao.adapter.MyHomeListAdapter;
import com.xiong.wuliao.entity.HomeStorys;
import com.xiong.wuliao.entity.Special;
import com.xiong.wuliao.entity.Urls;
import com.xiong.wuliao.entity.ZhuanTi;
import com.xiong.wuliao.interfaces.OnLoveClickListener;
import com.xiong.wuliao.util.HomeJSON;
import com.xiong.wuliao.util.LunBoPicJOSN;
import com.xiong.wuliao.util.ZhuanTiJSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 精选Fragment
 */
public class JingxuanFragment extends Fragment implements OnLoveClickListener{
	private SwipeRefreshLayout mySwipeRefreshLayoutJingXuan;
	private ListView myListViewJingXuan;

	// 刷新后请求服务器的参数
	private int offset = 0;
	// 是否到达页面底部的标注
	private boolean isBottom = false;
	// 保存服务器传过来的广告图片轮训的数据
	private List<String> picPath = new ArrayList<>();
	// 保存服务器传过来的ListView内的数据
	private List<HomeStorys> storysList = new ArrayList<>();
	// ListView的自定义适配器
	private MyHomeListAdapter adapter;
	// 给ListView加的头来展示广告图片轮训
	private ViewPager myViewPager;
	// 图片轮播的适配器
	private MyViewPagerAdapter myViewPagerAdapter;
	private boolean isLoop = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_jingxuan, container, false);
		isLoop = true;
		findView(view);
		return view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		isLoop = false;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
		setMyAdapter();
		setListener();
	}

	/**
	 * 给ListView加一个ViewPager的头来做图片轮训
	 */
	private void addListViewHead() {
		// 加载布局找到控件
		View view = LayoutInflater.from(getActivity()).inflate(R.layout.head_viewpager, null);
		myViewPager = (ViewPager) view.findViewById(R.id.myHeadViewPager);


		// 设置适配器
		myViewPagerAdapter = new MyViewPagerAdapter(getActivity());
		myViewPager.setAdapter(myViewPagerAdapter);
		myViewPager.setCurrentItem(myViewPagerAdapter.getCount() >> 1, false);
		myListViewJingXuan.addHeaderView(view);

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (isLoop) {
					try {
						Thread.sleep(3000);
						getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								int index = (myViewPager.getCurrentItem() + 1) % myViewPager.getAdapter().getCount();
								myViewPager.setCurrentItem(index);
							}
						});
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 设置监听事件
	 */
	private void setListener() {
		/**
		 * 上拉加载的监听
		 */
		myListViewJingXuan.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (isBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
					offset += 20;
					getJingXuanServerData();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				isBottom = firstVisibleItem + visibleItemCount == totalItemCount;
			}
		});

		/**
		 * 下拉刷新的监听
		 */
		mySwipeRefreshLayoutJingXuan.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				offset += 20;
				getJingXuanServerData();
			}
		});

		/**
		 * ListView的item点击事件
		 */
		myListViewJingXuan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				HomeStorys storys = storysList.get(position);
				String lastId = storys.getId();
				Intent intent = new Intent(getActivity(), SpecialActivity.class);
				intent.putExtra("lastId", lastId);
				startActivity(intent);
			}
		});

	}

	/**
	 * 设置适配器
	 */
	private void setMyAdapter() {
		adapter = new MyHomeListAdapter(getActivity(), storysList);
		myListViewJingXuan.setAdapter(adapter);
		// 设置接口
		adapter.setLoveListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		getPicServer();
		getJingXuanServerData();
	}

	/**
	 * 保存ListView的服务器数据
	 */
	private void getJingXuanServerData() {
		OkHttpUtils.get(Urls.JingXuanPath)
				.params("gender", 2)
				.params("limit", 20)
				.params("offset", offset)
				.params("generation", 2)
				.execute(new StringCallback() {
					@Override
					public void onSuccess(String s, Call call, Response response) {
						JSONObject jsonObject = null;
						try {
							jsonObject = new JSONObject(s.trim());
							String result = jsonObject.getString("message");
							if (result.equals("OK")) {

								storysList.addAll(HomeJSON.saveHomeStory(s.trim()));
								adapter.notifyDataSetChanged();
								mySwipeRefreshLayoutJingXuan.setRefreshing(false);
							} else {
								Toast.makeText(getActivity(), "数据请求失败", Toast.LENGTH_SHORT).show();
								mySwipeRefreshLayoutJingXuan.setRefreshing(false);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * 获取服务器图片轮播部分数据
	 */
	private void getPicServer() {
		OkHttpUtils.get(Urls.LunBoPath)
				.execute(new StringCallback() {
					@Override
					public void onSuccess(String s, Call call, Response response) {
						JSONObject jsonObject = null;
						try {
							jsonObject = new JSONObject(s.trim());
							String result = jsonObject.optString("message");
							if (result.equals("OK")) {
								picPath.addAll(LunBoPicJOSN.saveLunBoData(s.trim()));
								handler.sendEmptyMessage(100);
							} else {
								Toast.makeText(getActivity(), "服务器开小差了哟", Toast.LENGTH_SHORT).show();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			addListViewHead();
			myViewPagerAdapter.notifyDataSetChanged();
		}
	};

	/**
	 * 初始化控件
	 *
	 * @param view
	 */
	private void findView(View view) {
		mySwipeRefreshLayoutJingXuan = (SwipeRefreshLayout) view.findViewById(R.id.mySwipeRefreshLayoutJingXuan);
		myListViewJingXuan = (ListView) view.findViewById(R.id.myListViewJingXuan);

	}

	/**
	 * 接口回调
	 * @param view
	 */
	@Override
	public void loveClick(View view) {
		final int position = (int) view.getTag();
		if (storysList.get(position).isLiked()) {

		} else {
			SharedPreferences prefe = getActivity().getSharedPreferences("kkUser", getActivity().MODE_PRIVATE);
			String uid = "";
			uid = prefe.getString("id", "");
			if (uid.equals("")) {
				Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
			} else {
				OkHttpUtils.get(Urls.LovePath)
						.params("uid", uid)
						.params("aid", storysList.get(position).getId())
						.execute(new StringCallback() {
							@Override
							public void onSuccess(String s, Call call, Response response) {
								JSONObject jsonObject = null;
								try {
									jsonObject = new JSONObject(s.trim());
									String result = jsonObject.getString("message");
									if (result.equals("OK")) {
										storysList.get(position).setLiked(true);
										adapter.notifyDataSetChanged();
									} else {
										Toast.makeText(getActivity(), "点赞失败", Toast.LENGTH_SHORT).show();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});
			}
		}
	}

	/**
	 * 广告图片轮训适配器
	 */
	private class MyViewPagerAdapter extends PagerAdapter {
		Context context;

		public MyViewPagerAdapter(Context context) {
			this.context = context;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView imageView = new ImageView(context);
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			Picasso.with(context).load(picPath.get(position % picPath.size())).placeholder(R.mipmap.shiliimage01).into(imageView);
			container.addView(imageView);
			return imageView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}
}
